package com.zrt.pad.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import android.content.Context;

import com.zrt.pad.commonui.SharedApplication;

public class DataHandleUtil {

	public static final DataHandleUtil handle = new DataHandleUtil();
	
	private File parentFile;
	
	private DataHandleUtil(){
		Context context = SharedApplication.context;
		parentFile = context.getDir("Cache", Context.MODE_PRIVATE);
	}
	
	public boolean saveData(Serializable data, String name){
		String tmpName = name + ".tmp";
		File file = new File(parentFile, tmpName);
		if (file.exists()) {
			//删除失败，说明正在有人使用临时文件名
			if (file.delete() == false) {
				return false;
			}
		}
		try {
			FileOutputStream fos = new FileOutputStream(file);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(data);
			oos.close();
			fos.close();
			File destFile = new File(parentFile, name);
			if (destFile.exists()) {
				if (destFile.delete() == false) {
					throw new Exception("删除文件失败�?"+destFile.getAbsolutePath());
				}
			}
			if (file.renameTo(destFile) == false) {
				throw new Exception("重命名文件失败："+file.getAbsolutePath()+" to "+destFile.getName());
			}
		} catch (Exception e) {
			file.delete();
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	/**
	 * 从缓存文件中读取数据
	 * 读取成功后就删除已保存的文件，避免重复读�?
	 * @param name
	 * @return
	 */
	public Serializable readData(String name){
		File file = new File(parentFile, name);
		Serializable obj = null;
		try {
			FileInputStream fis = new FileInputStream(file);
			ObjectInputStream ois = new ObjectInputStream(fis);
			obj = (Serializable) ois.readObject();
			ois.close();
			fis.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		file.delete();
		return obj;
	}
	
	public boolean hasCacheStoraged(String name){
		File file = new File(parentFile, name);
		return file.exists();
	}
}
